﻿using CWD.BLL;
using CWD.DAL.DBUtility;
using CWD.RPT;
using CWD.XSD;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CWD.EF;
using CWD.Common;

namespace CWD
{
    public partial class fmInStock : Form
    {
        public int Id;
        public DbHelperSQL db;
        public DbHelperSQL dberp;
        public fmInStock()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            C_PoMaterial pm = new PoMaterialBLL().GetEntityByID(Id);
            if (pm.Auditer == null || pm.Auditer.Length == 0)
            {
                MessageBox.Show("当前到货单未生成，不能入库！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string Msg = "";
            Msg = ValidCode(tbBarCode.Text);
            if (Msg != "")
            {
                MessageBox.Show(Msg, "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (GeneRd(tbBarCode.Text,cbWhcode.SelectedValue.ToString(),out Msg))
            {
                if (Msg.Length == 10 && Msg.Substring(0, 2) == "RK")
                    ShowRd(Msg);
                else
                    MessageBox.Show(Msg, "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
                MessageBox.Show(Msg, "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        public Boolean GeneRd(string Codes,string WhCode,out string msg)
        {
            Codes = Codes.Replace("\r\n", ",");
            int affectrows;
            SqlParameter[] parameters = {
                new SqlParameter("@Codes", SqlDbType.NVarChar,500),
                new SqlParameter("@BusType", SqlDbType.NVarChar,10),
                new SqlParameter("@Whcode", SqlDbType.NVarChar,10),
                new SqlParameter("@Maker", SqlDbType.NVarChar,10),
                new SqlParameter("@msg", SqlDbType.NVarChar,500),
                new SqlParameter("@success", SqlDbType.Bit)
             };
            parameters[0].Value = Codes;
            parameters[1].Value = "委外加工";
            parameters[2].Value = WhCode;
            parameters[3].Value = Public.userName;
            parameters[4].Direction = ParameterDirection.Output;
            parameters[5].Direction = ParameterDirection.Output;

            db.RunProcedure("dbo.[CWD_GeneRd]", parameters, out affectrows);
            msg = parameters[4].Value.ToString();
            return parameters[5].Value.ToString().ToLower() == "true" ? true : false;
        }
        public string ValidCode(string Codes)
        {
            string msg = "";
            Codes = Codes.Replace("\r\n", ",");
            if (Codes.IndexOf(',') <= 0)
                return "托盘编码和包装编码之间请用逗号分隔！";
            Codes = Codes.TrimEnd(',');
            string[] arCode = Codes.Split(',');
            string sql = string.Format("select COUNT(1) from Position where cWhCode = '{0}' and cPosCode = '{1}'", cbWhcode.SelectedValue, arCode[0]);
            var oj = dberp.GetSingle(sql);
            if (Common.Common.GetInt(oj) == 0 )
            {
                msg = string.Format("输入的托盘编码不存在，您确定要增加吗？");
                if (MessageBox.Show(msg, "数据检查", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return "指定的托盘号不正确，不能保存！";
                msg = "";
            }
                //if (arCode[0].Length != 6 || !Common.Common.IsDecimal(arCode[0]))
                //return "托盘编码必须为6位数字！";
            for (int i = 1; i < arCode.Length; i++)
            {
                if(arCode[i].Length!=9 && arCode[i].Substring(0,1)!="M")
                    return "包装编码必须为M起头后接8位数字！";
            }
            sql = string.Format("select id from(select id from dbo.CWD_SplitStringToTable('{0}', ',')) tmp group by id having COUNT(id) > 1", Codes);
            oj = db.GetSingle(sql);
            if (oj != null && oj.ToString() != "")
            {
                return string.Format("包装编码{0}重复，不能生成入库单！", oj.ToString());
            }
            sql = string.Format("select stuff((select ','+id from (select id from dbo.CWD_SplitStringToTable('{0}',',') tmp where id not in (select packetno from ekk..C_PoMaterialList where Id={1})) per  for xml path('')), 1, 1, '') ", Codes.Substring(Codes.IndexOf(',')+1,Codes.Length-Codes.IndexOf(',')-1),Id);
            oj = db.GetSingle(sql);
            if (oj!=null && oj.ToString() != "")
                return string.Format("包装编码{0}不在当前到货单中，不能生成入库单！",oj.ToString());
            sql = string.Format("select STUFF((select ','+id from (select tmp.id from dbo.CWD_SplitStringToTable('{0}', ',') tmp inner join UFDATA_001_2018..rdrecords rds on tmp.id=rds.cDefine28) per  for xml path('')), 1, 1, '')", Codes);
            oj = db.GetSingle(sql);
            if (oj != null && oj.ToString() != "")
            {
                return string.Format("包装编码{0}已经入库，不能重复生成入库单！", oj.ToString());
            }
            return msg;
        }
        private void ShowRd(string Code)
        {
            if (Code == "")
            {
                tbCode.Text = "";
                tbBarCode.Text = "";
                //tbMaker.Text = "";
                dgv.DataSource = null;
                return;
            }
            string sql = "select ID,cCode,dDate,cMaker from UFDATA_001_2018..RdRecord rd where cCode='" +Code+"'";
            DataSet ds = db.Query(sql);
            tbCode.Text = ds.Tables[0].Rows[0]["cCode"].ToString();
            dtMaker.Value = DateTime.Parse(ds.Tables[0].Rows[0]["dDate"].ToString());
            //tbMaker.Text= ds.Tables[0].Rows[0]["cMaker"].ToString();
            int Id = Common.Common.GetInt(ds.Tables[0].Rows[0]["Id"]);
            sql = string.Format("select irowno 行号,cinvcode 存货编码,cinvname 存货名称,cinvstd 存货规格,cinvdefine1 颜色,cbatch 批号, cast(iquantity as numeric(10,1)) 数量, cinvm_unit 计量 from UFDATA_001_2018..recordinsq where ID={0}", Id);
            DataSet ds1 = db.Query(sql);
            Common.Common.SetDgvData(dgv, ds1.Tables[0]);
            dgv.Columns[0].Width = 30;
            dgv.Columns[1].Width = 120;
            dgv.Columns[2].Width = 150;
            dgv.Columns[3].Width = 250;
            dgv.Columns[4].Width = 80;
            dgv.Columns[5].Width = 200;
            dgv.Columns[6].Width = 70;
            dgv.Columns[7].Width = 30;
            tbBarCode.Text = "";
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            string prnName = "";
            var rlt = new PrintSetBLL().GetQuery().Where(p => p.Module == "面料入库" && p.User == Public.userCode).Select(p => new { p.Printer, p.PaperSize, p.PaperID }).ToList();
            if (rlt.Count > 0)
                prnName = rlt[0].Printer;
            else
            {
                prnName = Printers.LocalPrinter.DefaultPrinter();
            }

            if (prnName == "")
            {
                MessageBox.Show("请设置打印机！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            string sql = "select ID,cCode,dDate,cMaker,cBusType,ven.cvenname from UFDATA_001_2018..RdRecord rd left join UFDATA_001_2018..vendor ven on rd.cVenCode=ven.cvencode where cCode='" + tbCode.Text + "'";
            DataSet ds = db.Query(sql);
            MTab dsPrint = new MTab();
            DataRow drMain = dsPrint.Tables["RdRecord"].NewRow();
            drMain["cCode"]=ds.Tables[0].Rows[0]["cCode"].ToString();
            drMain["cBusType"] = ds.Tables[0].Rows[0]["cBusType"].ToString();
            drMain["cMaker"] = ds.Tables[0].Rows[0]["cMaker"].ToString();
            drMain["cVenName"] = ds.Tables[0].Rows[0]["cVenName"].ToString();
            drMain["dDate"] =DateTime.Parse(ds.Tables[0].Rows[0]["dDate"].ToString()).ToString("yyyy-MM-dd");
            dsPrint.Tables["RdRecord"].Rows.Add(drMain);
            int Id = Common.Common.GetInt(ds.Tables[0].Rows[0]["Id"]);
            sql = string.Format("select irowno 行号,cinvcode 存货编码,cinvname 存货名称,cinvstd 存货规格,cinvdefine1 颜色,cbatch 批号, iquantity 数量, cinvm_unit 计量,cPosition from UFDATA_001_2018..recordinsq where ID={0}", Id);
            DataSet ds1 = db.Query(sql);            
            for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
            {
                if(i==0 && ds1.Tables[0].Rows[i]["cPosition"] !=null && ds1.Tables[0].Rows[i]["cPosition"] !=DBNull.Value)
                    drMain["Position"]= ds1.Tables[0].Rows[i]["cPosition"];
                DataRow dr = dsPrint.Tables["RdRecords"].NewRow();
                dr["iRowNo"] = dgv.Rows[i].Cells["行号"].Value.ToString();
                dr["cInvCode"] = dgv.Rows[i].Cells["存货编码"].Value.ToString();
                dr["cInvName"] = dgv.Rows[i].Cells["存货名称"].Value.ToString();
                dr["cInvStd"] = dgv.Rows[i].Cells["存货规格"].Value.ToString();
                dr["iQuantity"] = dgv.Rows[i].Cells["数量"].Value.ToString();
                dr["Unit"] = dgv.Rows[i].Cells["计量"].Value.ToString();
                dr["CBatch"] = dgv.Rows[i].Cells["批号"].Value.ToString();                
                dsPrint.Tables["RdRecords"].Rows.Add(dr);
            }
            //fmReport fmReport = new fmReport();
            crRd  crt = new crRd();
            crt.SetDataSource(dsPrint);
            crt.PrintOptions.PrinterName = prnName;
            crt.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Portrait;
            crt.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.DefaultPaperSize;
            crt.PrintToPrinter(1, true, 1, 1);
            //fmReport.crystalReportViewer1.ReportSource = crt;
            //fmReport.ShowDialog();
        }

        private void fmInStock_Resize(object sender, EventArgs e)
        {
            dgv.Height = this.ClientRectangle.Height - plMain.Height;            
            dgv.Width = this.ClientRectangle.Width - tbBarCode.Width;
            tbBarCode.Height = dgv.Height;
        }

        private void fmInStock_Load(object sender, EventArgs e)
        {
            dgv.Height = this.ClientRectangle.Height - plMain.Height;
            dgv.Top = plMain.Bottom;
            string connectionstr = ConfigurationManager.ConnectionStrings["EKKDB"].ToString();
            db = new DbHelperSQL(connectionstr);
            dberp = new DbHelperSQL(ConfigurationManager.ConnectionStrings["ERPDB"].ToString());
            string sql = string.Format("select cWhCode,cWhName from UFDATA_001_2018..Warehouse where cWhCode in ('101','221','224')");
            DataSet ds = db.Query(sql);
            cbWhcode.DataSource = ds.Tables[0];
            cbWhcode.DisplayMember = "cWhName";
            cbWhcode.ValueMember = "cWhCode";
            cbWhcode.SelectedIndex = 0;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            string RdCode = tbCode.Text;
            if (RdCode.Length <= 0)
                return;
            string sql = string.Format("select ISNULL(cHandler,'') as cHandler from ufdata_001_2018..rdrecord where cCode='{0}'", RdCode);
            DataSet ds = db.Query(sql);
            if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["cHandler"].ToString() != "")
            {
                MessageBox.Show("当前入库单已经审核，不能删除！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            string msg = "";
            int affectrows;
            SqlParameter[] parameters = {
                new SqlParameter("@Code", SqlDbType.NVarChar,500),
                new SqlParameter("@bAudit", SqlDbType.SmallInt),
                new SqlParameter("@caccid", SqlDbType.VarChar,20),
                new SqlParameter("@msg", SqlDbType.NVarChar,500),
                new SqlParameter("@success", SqlDbType.Bit)
             };
            parameters[0].Value = RdCode;
            parameters[1].Value = 0;
            parameters[2].Value = "UFDATA_001_2018";
            parameters[3].Direction = ParameterDirection.Output;
            parameters[4].Direction = ParameterDirection.Output;

            db.RunProcedure("dbo.[CWD_DelOmRd]", parameters, out affectrows);
            msg = parameters[3].ToString();
            if (parameters[4].Value.ToString().ToLower() != "true")
                MessageBox.Show(parameters[3].Value.ToString(), "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                ShowRd(GetLastCode(Id));
            }
            this.Cursor = Cursors.Default;
        }
        private string GetLastCode(int Id)
        {
            string sql = string.Format("select top 1 rd.cCode from UFDATA_001_2018..RdRecord rd INNER join UFDATA_001_2018..RdRecords rds on rd.ID = rds.ID inner join EKK..C_PoMaterialList pms on rds.cbarcode = pms.PacketNo where pms.Id = {0} order by rd.cCode desc", Id);
            object oj = db.GetSingle(sql);
            if (oj != null)
                return oj.ToString();
            else
                return "";
        }
    }
}
